package com.wkbb.common.utils;

import java.math.BigInteger;
import java.security.MessageDigest;

public class MD5Util {

	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
            n += 256;
        }
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
            }
		} catch (Exception exception) {

		}
		return resultString;
	}
	
	/**
	 * 获取经过MD5加密后的字符串
	 * @param plainText 要加密的字符串
	 * @return 经过MD5算法加密的字符串形式的32位16进制,如果参数表示的字符串为空，返回null
	 */
	public static String getMD5Code(String plainText) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(plainText.getBytes());
			String bi = new BigInteger(1, md5.digest()).toString(16);
			return fillMD5(bi);
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String fillMD5(String md5){
		return md5.length()==32?md5:fillMD5("0"+md5);
	}
	
	public static void main(String[] args) { 
        String ss = MD5Util.getMD5Code("123456");
        System.err.print(ss);
    }  
}
